<template>
  <div class="model-market">
    <div class="page-card">
    <!-- <div style="margin-left: 20px;font-weight: bold;color: rgb(66,66,100);">
      模型广场
    </div> -->
     <!-- <el-divider /> -->
    <!-- 搜索和筛选区域 -->
    <div class="search-section">
      <!-- 筛选标题和搜索 -->
      <div class="filter-header">
        <div >
          <h3 class="filter-title">全部服务</h3>
         
        </div>
        <div class="search-section-right">
          <el-input
            v-model="searchQuery"
            placeholder="从全部模型中搜索"
            @input="handleSearch"
            clearable
            class="search-input-el"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
        </div>
      </div>
      
      <!-- 筛选条件 -->
      <div  >
        <!-- 分类筛选 -->
        <div class="filter-group">
          <div class="filter-row">
            <div class="filter-label">分类</div>
            <div class="filter-options">
              <button 
                v-for="category in categories" 
                :key="category.dictValue"
                :class="['filter-option', { active: activeCategory === category.dictValue }]"
                @click="filterByCategory(category.dictValue)"
              >
                {{ category.dictLabel }}
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 加载状态 -->
    <div v-if="loading" class="loading-container">
      <div class="loading-spinner"></div>
      <p>正在加载服务列表...</p>
    </div>

    <!-- API服务卡片网格 -->
    <div v-else class="models-grid">
      <div 
        v-for="service in filteredServices" 
        :key="service.apiId"
        class="model-card"
      >
        <!-- 卡片头部：图标 + 标题 + 标签 -->
        <div class="card-header">
          <!-- 左侧图标 -->
          <!-- <div class="service-icon">
            <svg width="48" height="48" viewBox="0 0 24 24" fill="none" stroke="currentColor">
              <path d="M12 2L2 7l10 5 10-5-10-5z"></path>
              <path d="M2 17l10 5 10-5"></path>
              <path d="M2 12l10 5 10-5"></path>
            </svg>
          </div> -->
          
          <!-- 右侧内容区 -->
          <div class="header-content">
            <!-- 标题行 -->
            <div class="title-row">
              <h3 class="model-name">{{ service.apiName }}</h3>
              <div class="status-area">
                <span v-if="service.status === '0'" class="status-badge status-active">正常</span>
                <span v-else class="status-badge status-inactive">停用</span>
              </div>
            </div>
            
            <!-- 标签行 -->
            <div class="tags-row" v-if="service.apiTag">
              <span 
                v-for="(tag, index) in service.apiTag.split(',')" 
                :key="index"
                class="tag-item"
              >
                {{ tag.trim() }}
              </span>
            </div>
          </div>
        </div>
        
        <!-- 描述区域 -->
        <div class="card-description">
          <p class="model-description">{{ service.apiDescription }}</p>
        </div>
        
        <!-- 分类和更新时间 -->
        <div class="card-meta">
          <div class="meta-left">
            <span class="category-label">{{ getServiceTypeName(service.apiType) }}</span>
          </div>
          <div class="meta-right">
            <span class="update-time">{{ formatDate(service.updateTime) }}更新</span>
          </div>
        </div>
        
        <!-- 分割线 -->
        <div class="divider"></div>
        
        <!-- 操作按钮 -->
        <div class="model-actions">
          <button class="btn-action" @click="createApplication(service)" :disabled="service.status !== '0'">
            <el-icon class="action-icon">
              <TopRight />
            </el-icon>
            立即体验
          </button>
        </div>
      </div>
    </div>

    
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { TopRight, Search } from '@element-plus/icons-vue'
import { apiServiceAPI } from '@/api/agriculture/xctl/apiService'

const router = useRouter()

// 响应式数据
const searchQuery = ref('')
const activeCategory = ref('all')
const loading = ref(false)
const apiServices = ref([])
const originalServices = ref([])
const categories = ref([])

// 获取分类数据
const fetchCategories = async () => {
  try {
    const baseURL = import.meta.env.VITE_API_BASE_URL || 'http://localhost:8080'
    const response = await fetch(`${baseURL}/noAuth/api/type/list`)
    const data = await response.json()
    if (data.code === 200) {
      // 添加"全部"选项
      categories.value = [
        { dictValue: 'all', dictLabel: '全部' },
        ...data.rows
      ]
    } else {
      console.error('获取分类列表失败:', data.msg)
    }
  } catch (error) {
    console.error('获取分类列表出错:', error)
  }
}

// 获取API服务列表
const fetchApiServices = async () => {
  try {
    loading.value = true
    const response = await apiServiceAPI.getApiServiceList()
    if (response.code === 200) {
      originalServices.value = response.rows || []
      apiServices.value = [...originalServices.value]
    } else {
      console.error('获取API服务列表失败:', response.msg)
    }
  } catch (error) {
    console.error('获取API服务列表出错:', error)
  } finally {
    loading.value = false
  }
}

// 计算属性：过滤后的服务
const filteredServices = computed(() => {
  return apiServices.value
})

// 搜索处理
const handleSearch = () => {
  let filtered = [...originalServices.value]
  
  // 按分类过滤
  if (activeCategory.value !== 'all') {
    filtered = filtered.filter(service => service.apiType === activeCategory.value)
  }
  
  // 按搜索关键词过滤
  if (searchQuery.value.trim()) {
    const query = searchQuery.value.toLowerCase()
    filtered = filtered.filter(service => 
      service.apiName.toLowerCase().includes(query) ||
      service.apiDescription.toLowerCase().includes(query)
    )
  }
  
  apiServices.value = filtered
}

// 按分类过滤
const filterByCategory = (categoryId) => {
  activeCategory.value = categoryId
  handleSearch()
}

// 清空所有筛选条件
const clearAllFilters = () => {
  activeCategory.value = 'all'
  searchQuery.value = ''
  handleSearch()
}

// 清空筛选条件（用于清空按钮）
const clearFilters = () => {
  activeCategory.value = 'all'
  searchQuery.value = ''
  handleSearch()
}

// 获取服务类型名称
const getServiceTypeName = (apiType) => {
  const category = categories.value.find(cat => cat.dictValue === apiType)
  return category ? category.dictLabel : '未知类型'
}

// 获取服务类型样式类
const getServiceTypeClass = (apiType) => {
  const classMap = {
    '0': 'type-disease',
    '1': 'type-pest',
    '2': 'type-growth'
  }
  return classMap[apiType] || 'type-default'
}

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return date.toLocaleDateString('zh-CN')
}



// 创建应用
const createApplication = (service) => {
  if (service.status !== '0') {
    alert('该服务当前不可用')
    return
  }
  // 跳转到应用创建页面，传递服务信息
  const serviceData = encodeURIComponent(JSON.stringify(service))
  router.push(`/agricultureXctl/create-app?service=${serviceData}`)
}

// 查看详情
const viewDetails = (service) => {
  console.log('查看服务详情:', service)
  alert(`查看服务详情: ${service.apiName}`)
}

// 组件挂载时获取数据
onMounted(() => {
  fetchCategories()
  fetchApiServices()
})
</script>

<style scoped>
.model-market {
  margin: 0 auto;
  background: #ffffff;
  border-radius: 6px;
  padding-top: 20px;
  border: 1px solid #f0f0f0;
}
 
 
.page-header {
  text-align: center;
  margin-bottom: 48px;
}

.page-title {
  font-size: 36px;
  font-weight: 700;
  color: #333;
  margin-bottom: 16px;
}

.page-description {
  font-size: 18px;
  color: #6b7280;
  max-width: 600px;
  margin: 0 auto;
  line-height: 1.6;
}

.search-section {
 
  padding: 24px;
 
  margin-bottom: 32px;
}

.filter-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  gap: 16px;
}

.search-section-right {
  flex-shrink: 0;
}

 
 

.filter-title {
  font-size: 18px;
  font-weight: bold;
  color: #333;
  margin: 0;
}

 

 
.filter-group {
  margin-bottom: 20px;
}

.filter-group:last-child {
  margin-bottom: 0;
}

.filter-row {
  display: flex;
  align-items: center;
  gap: 16px;
}

.filter-label {
  font-size: 12px;
   
  color: rgb(113,111,141);
  flex-shrink: 0;
}

.filter-options {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
  flex: 1;
}

.filter-option {
  padding: 3px 12px;
  border: none;
  background: transparent;
  color: rgb(113,111,141);
  border-radius: 6px;
  cursor: pointer;
  font-size: 13px;
  transition: all 0.2s ease;
  white-space: nowrap;
}

.filter-option:hover {
  background: rgb(238, 236, 251);
  color: rgb(136, 94, 237);
}

.filter-option.active {
  background: rgb(238, 236, 251);
  color: rgb(136, 94, 237);
}

.models-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(350px, 1fr));
  gap: 24px;
  margin-bottom: 48px;
  margin-left: 20px;
  margin-right: 20px;
}

.model-card {
  background: linear-gradient(135deg, rgb(244, 244, 246) 20%,#fff 35%, #fff 100%);
  border: 1px solid #e5e7eb;
  border-radius: 12px;
  overflow: hidden;
 
  transition: transform 0.2s ease, box-shadow 0.2s ease;
}

.model-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.15);
}

.card-header {
  display: flex;
  align-items: flex-start;
  padding: 20px;
  /* height: 48px; */ /* 移除固定高度 */
  min-height: 48px; /* 改为最小高度 */
  gap: 16px;
}

.service-icon {
  flex-shrink: 0;
  width: 48px;
  height: 48px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
}

.header-content {
  flex: 1;
  margin-left: 0px;
  min-width: 0;
}

.card-description {
  margin:  0;
  margin-bottom: 6px;
  padding: 0 16px;
}

.title-row {
  display: flex;
  align-items: flex-start;
  justify-content: space-between;
  margin-bottom: 4px;
  gap: 12px;
}

.status-area {
  display: flex;
  gap: 6px;
  flex-shrink: 0;
}

.tags-row {
  display: flex;
  flex-wrap: wrap;
  gap: 6px;
  margin-bottom: 8px;
}

.tag-item {
  padding: 3px 8px;
  background: rgb(248,248,250);
  color: rgb(156,154,174);
  border-radius: 6px;
  font-size: 11px;
  font-weight: 500;
  
}

.model-badge {
  padding: 4px 8px;
  border-radius: 12px;
  font-size: 11px;
  font-weight: 500;
  color: white;
}

.type-disease {
  background: #ef4444;
}

.type-pest {
  background: #f59e0b;
}

.type-growth {
  background: #22c55e;
}

.type-default {
  background: #3b82f6;
}

.status-badge {
  padding: 4px 8px;
  border-radius: 12px;
  font-size: 11px;
  font-weight: 500;
}

.status-active {
  background: #22c55e;
  color: white;
}

.status-inactive {
  background: #6b7280;
  color: white;
}

.model-name {
  font-size: 16px;
  
  color: #111827;
  margin: 0;
  line-height: 1.4;
}

.model-description {
  color: #6b7280;
  line-height: 1.5;
  margin: 0;
  font-size: 14px;
}

.card-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 20px;
  margin-bottom: 16px;
}

.meta-left .category-label {
  color: rgb(201,200,210);
  font-weight: 500;
  font-size: 12px;
}

.meta-right .update-time {
  color: rgb(201,200,210);
  font-size: 13px;
}

.divider {
  height: 1px;
  background: #f3f4f6;
  margin: 0 20px 16px 20px;
}



.loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60px 20px;
  color: #6b7280;
}

.loading-spinner {
  width: 40px;
  height: 40px;
  border: 4px solid #f3f4f6;
  border-top: 4px solid #3b82f6;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: 16px;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}





.model-actions {
  display: flex;
  gap: 12px;
  padding: 0 20px 20px 20px;
}

.btn-action {
  background: none;
  color: #374151;
  border: none;
  
  border-radius: 6px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.2s ease;
  font-size: 14px;
  display: flex;
  align-items: center;
  gap: 6px;
  width: 100%;
  justify-content: center;
}

.btn-action:hover {
  color: #3b82f6;
}

.btn-action:disabled {
  color: #9ca3af;
  cursor: not-allowed;
  opacity: 0.6;
}

.btn-action:disabled:hover {
  color: #9ca3af;
}

.action-icon {
  font-size: 16px;
  transition: transform 0.2s ease;
}

.btn-action:hover .action-icon {
  transform: translate(2px, -2px);
}

.load-more {
  text-align: center;
}

.btn-load-more {
  background: #fff;
  color: #007bff;
  border: 2px solid #007bff;
  padding: 16px 32px;
  border-radius: 8px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.2s ease;
}

.btn-load-more:hover {
  background: #007bff;
  color: white;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .model-market {
    padding: 20px 16px;
  }
  
  .page-title {
    font-size: 28px;
  }
  
  .models-grid {
    grid-template-columns: 1fr;
  }
  
  .filter-tabs {
    justify-content: flex-start;
    overflow-x: auto;
    padding-bottom: 8px;
  }
  
  .model-actions {
    flex-direction: column;
  }
}
</style>